# // datatype:   player      用户 {'datatype':'player', 'name':nickname, 'comm':'reg'}
# //             msg         消息 { 'datatype':'msg', 'srcName': nickname, 'disName':nickname, 'content': text.value}
# //             room        房间
import json

player_list = {}

async def websocket_application(scope,receive, send):

    while(True):
        event = await receive()
        type = event['type']

        if type == 'websocket.connect':
            await send({'type':'websocket.accept'})
            print('[LOG] 连接已建立', event)
        elif type == 'websocket.disconnect':
            break
        elif type == 'websocket.receive':
            # 接收数据处理
            getstr = event['text']
            print('[MSG]', getstr)
            # 字符串-->数据
            get_data = json.loads(getstr)
            datatype = get_data['datatype']
            
            # 按照'datatype'的值来判断该做什么
            # 玩家
            if datatype == 'player':
                player = get_data['name']
                comm = get_data['comm']
                players = list(player_list.keys())
                # 登录用户
                if comm == 'reg' and not (player in players):
                    player_list[player] = send
                # 登出用户
                elif comm == 'remove' and (player in players):
                    del player_list[player]

                players = list(player_list.keys())    
                sanddata = {
                    'datatype':datatype, 
                    'comm':'list', 
                    'player_list':players
                    }
                await broadcast(sanddata)

            # 消息
            if datatype == 'msg':
                disName  = get_data['disName']
                sanddata = get_data
                # 发送
                sendstr = json.dumps(sanddata)
                await player_list[disName]({
                    'type':'websocket.send',
                    'text':sendstr
                })            
            if datatype == 'room':
                pass


        else:
            raise Exception('[ERR] Unknown received type :', type)

async def broadcast(data):
    sendstr = json.dumps(data)
    players = list(player_list.keys())
    for p in players:
       await player_list[p]({
            'type':'websocket.send',
            'text':sendstr
        })     